package com.xu.common.exception;

import com.xu.common.domain.MyResult;
import com.xu.common.domain.MyResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理类
 *
 * @author xu
 * 2022/7/19 16:16
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 自定义异常处理
     */
    @ExceptionHandler(MyException.class)
    public MyResult myException(MyException myException){
        log.error(myException.getMsg());
        return MyResult.fail(myException.getCode(),myException.getMsg());
    }

    /**
     * json 序列化异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public MyResult httpMessageNotReadableException(HttpMessageNotReadableException e){
        e.printStackTrace();
        return MyResult.fail("请传入json");
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public MyResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldErrors().get(0);
        return MyResult.fail(fieldError.getDefaultMessage());
    }


    /**
     * 未捕获异常
     */
    @ExceptionHandler(Exception.class)
    public MyResult exception(Exception exception){
        exception.printStackTrace();
        return MyResult.fail(MyResultCode.SYS_ERROR,"系统错误");
    }
}
